package com.guigu.tms.dispatch.controller;

import com.guigu.tms.commons.dispatch.entity.ScheduleJob;
import com.guigu.tms.dispatch.service.IScheduleJobService;
import com.guigu.tms.dispatch.utils.ScheduleUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/scheduleJob")
public class ScheduleJobController {
    @Autowired
    private Scheduler scheduler;

    @Autowired
    private IScheduleJobService schedulerJobService;

    /**
     * 添加定时任务
     * @param scheduleJob
     * @return
     */
    @PostMapping("create")
    public String save(@RequestBody ScheduleJob scheduleJob) {
        //构建job信息
        ScheduleUtils.createScheduleJob(scheduler,scheduleJob);
        return "OK";
    }

    /**
     * 暂停定时任务
     * @param jobId
     * @return
     */
    @PutMapping("/pause/{jobId}")
    public String pause(@PathVariable String jobId) throws Exception{
        ScheduleUtils.pauseJob(scheduler,jobId);
        schedulerJobService.updateStatus(jobId,0);
        return "OK";
    }

    /**
     * 恢复定时任务
     * @param jobId
     * @return
     */
    @PutMapping("/resume/{jobId}")
    public String resume(@PathVariable String jobId) throws Exception{
        ScheduleUtils.resumeJob(scheduler,jobId);
        schedulerJobService.updateStatus(jobId,1);
        return "OK";
    }

    /**
     * 立即执行定时任务
     * @param jobId
     * @return
     */
    @PutMapping("/run/{jobId}")
    public String run(@PathVariable String jobId) throws Exception{
        ScheduleJob scheduleJob = schedulerJobService.getScheduleJob(jobId);
        ScheduleUtils.run(scheduler,scheduleJob);
        return "OK";
    }

    /**
     * 更新定时任务
     * @param scheduleJob
     * @return
     * @throws Exception
     */
    @PutMapping("/update")
    public String update(@RequestBody ScheduleJob scheduleJob) {
        System.out.println(scheduleJob);
        ScheduleUtils.updateScheduleJob(scheduler,scheduleJob);
        System.out.println(scheduleJob);
        schedulerJobService.update(scheduleJob);
        return "OK";
    }

}
